package com.petAdoption.manager.config;


import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.petAdoption.manager.entity.Employee;
import com.petAdoption.manager.exception.ServiceException;
import com.petAdoption.manager.mapper.EmployeeMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//Jwt拦截器
@Configuration
public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private EmployeeMapper employeeMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) token = request.getParameter("token");
        if (handler instanceof HandlerMethod) {
            AuthAccess authAccess = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
            if (authAccess != null) return true;
        }

        if (StrUtil.isBlank(token)) throw new ServiceException("401","请登录");

        //获取token信息
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new ServiceException("401", "请登录");
        }

        //根据id查询数据库
       Employee employee = employeeMapper.selectById(userId);
        if (employee == null) throw new ServiceException("401", "请登录");
        //用户密码加签名验证
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(employee.getEmployeePassword())).build();
        try {
            jwtVerifier.verify(token);//验证token
        } catch (JWTDecodeException j) {
            throw new ServiceException("401", "请登录");
        }
        return true;
    }

}
